package com.datastructure.linkedlist;

/**
 * @author: 临晖
 * @date: 2023/10/11
 * @description:
 */


import com.sun.security.auth.NTDomainPrincipal;

import javax.swing.event.MouseInputAdapter;

/**
 * 设计列表
 */
public class Solution02 {

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        list.addAtIndex(0, 20);
        list.addAtIndex(0, 20);
        list.addAtIndex(1, 30);
        System.out.println(list.get(0));

    }
}

class MyLinkedList {

    Node head;
    int size;

    public MyLinkedList() {
        head = null;
        size = 0;
    }

    public int get(int index) {
        int rs = -1;
        if (index < 0 || index >= size) {
            return rs;
        }
        Node node = head;
        for (int i = 0; i < size; i++) {
            if (i == index) {
                rs = node.val;
            }
            if (node.next != null) {
                node = node.next;
            }

        }

        return rs;
    }

    public void addAtHead(int val) {
        Node node = new Node(val, head);
        head = node;
        size++;
    }

    public void addAtTail(int val) {
        Node node = new Node(val, null);
        size++;
        if (head == null) {
            head  = node;
            return;
        }

        Node last = head;
        while (last.next != null) {
            last = last.next;
        }

        last.next = node;
    }

    public void addAtIndex(int index, int val) {
        if (index < 0 || index > size) {
            return;
        }


        Node pre = new Node(0, head);
        Node first = pre;
        Node node = new Node(val, null);
        for (int i = 0; i <= size; i++) {
            if (i == index) {
                 node.next = pre.next;
                 pre.next = node;
                 size++;
                 break;
            } else if (pre.next == null && index == size) {
                pre.next = node;
                size++;
            }

            pre = pre.next;
        }
        //这里需要一层保险
        head = first.next;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        Node pre = new Node(0,head);
        Node first = pre;
        for (int i = 0; i < size; i++) {
            if (i == index) {
                pre.next = pre.next.next;
                size--;
                head = first.next;
                return;
            }
            pre = pre.next;
        }
        head = first.next;
    }
}


class Node {
    int val;
    Node next;

    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }

    public Node(int val) {
        this.val = val;
    }

    public Node() {
    }
}